package com.ys.controller.api.storage;

import com.alibaba.fastjson.JSON;
import com.ys.config.MenuId;
import com.ys.entity.base.TbCountry;
import com.ys.entity.storage.TccLogisticsChannelDetail;
import com.ys.entity.storage.TccWarehouse;
import com.ys.entity.sys.YsCol;
import com.ys.mapper.storage.StorageMapper;
import com.ys.service.storage.TccLogisticsChannelDetailService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Author: fxz
 * @CreateTime: 2024-12-05
 * @Description: 物流渠道详情
 * @Version: 1.5
 */
@Controller
@RequestMapping("/api/inter/tccLogisticsChannelDetail")
public class ApiInterTccLogisticsChannelDetailController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTccLogisticsChannelDetailController.class);

    @Autowired
    private TccLogisticsChannelDetailService tccLogisticsChannelDetailService;

    @Autowired
    private CommonApiService<TccLogisticsChannelDetail> commonApiService;

    //菜单id
    private Long menuId = MenuId.TCC_LogisticsChannelDetail;

    @Autowired
    private StorageMapper storageMapper;
    /**
     * 查询
     */
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TccLogisticsChannelDetail cond, String conditions
    ){
        try {
            cond = setSeachSql(cond);
            LayuiTableVoJA setList = commonApiService.searchLay(cond);
            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }



    /**
     /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TccLogisticsChannelDetail setSeachSql(TccLogisticsChannelDetail cond){

        cond.addLeftJoin("TCC_Warehouse B ON B.Cck=A.Cck")
                .addLeftJoin("TB_Country C ON C.Code=A.Country")
                .addField("B.Vck vck,C.Name destinationCountryName")
                //排序
                .setOrderby("A.CreateTime DESC");

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }



    @RequestMapping("/searchFbaPlan")
    @ResponseBody
    public LayuiTableVoJA searchFbaPlan(@ModelAttribute TccLogisticsChannelDetail cond,Long shopId){
        cond    .addField("case when divisionalRule = 0 then '0.1kg进1kg' when divisionalRule = 1 then '0.5kg进1kg' else '不约分' end as divisionalRuleName")//约分规则
                .addField("case when coefficientWeight = 0 then '5000'else '6000' end as coefficientWeightName")//抛货系数
                .addLeftJoin("TCC_Warehouse F ON F.Cck = A.Cck")
                .addLeftJoin("TP_AmazonShop B ON B.id = " + shopId)
                .addLeftJoin("TB_Site C ON C.id = B.SiteId")
                .addLeftJoin("TB_Country D ON D.id = C.CountryId")
                .setStatus(1)
                .where("D.Code = A.Country")
        ;
        LayuiTableVoJA vo = commonApiService.searchLay(cond);
        return vo;
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccLogisticsChannelDetail cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond)
                    .addField("CASE WHEN A.TransportationId=0 THEN '快递' WHEN A.TransportationId=1 THEN '空运'" +
                            "WHEN A.TransportationId=2 THEN '卡航' WHEN A.TransportationId=3 THEN '铁路' " +
                            "WHEN A.TransportationId=4 THEN '海运' END  transportationName")
                    .addField("CASE WHEN A.NameLogsticsClearance=1 THEN '包税' WHEN A.NameLogsticsClearance=0 THEN '自税'" +
                            " END logsticsClearanceName");

            TccLogisticsChannelDetail tccLogisticsChannelDetail = JSON.parseObject(JSON.toJSONString(cond), TccLogisticsChannelDetail.class);
            TccWarehouse tccWarehouse = JSON.parseObject(JSON.toJSONString(cond), TccWarehouse.class);
            TbCountry tbCountry = new TbCountry().setCode(cond.getCountry());

            String transportationName = ConditionUtil.getConditionValue(conditions, "transportationId");//运输类型

            String nameLogsticsClearance = ConditionUtil.getConditionValue(conditions, "nameLogsticsClearance");//清关方式

            String logsticsWay = ConditionUtil.getConditionValue(conditions, "logsticsWay");//物流服务名称
            if (logsticsWay != null){
                cond.where("[逸博" + tccWarehouse.getVck()+"]" +tbCountry.getName()+transportationName+"("+nameLogsticsClearance+")"+
                        tccLogisticsChannelDetail.getEstimatedDayFrom()+"~"+ tccLogisticsChannelDetail.getEstimatedDayTo()+"天"  );
            }

            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setFrontExport(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TccLogisticsChannelDetail> util = new ExportExcelUtils<>(new TccLogisticsChannelDetail());
            String toFilePath = util.exportExcel(listData, listField, "物流渠道详情");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    @RequestMapping("/searchPlan")
    @ResponseBody
    public LayuiTableVoJA searchPlan(@ModelAttribute TccLogisticsChannelDetail cond){
        return commonApiService.searchLay(cond);
    }

}
